package com.itheima.admin.aop;
import cn.hutool.jwt.JWT;
import com.itheima.xo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author :WuJunJie
 * packageName :com.itheima.admin.aop
 * fileName :AOP
 * creationTime :2022-11-11 14:57
 */
@Component
@Aspect
@Slf4j
public class AOP {

//    @Pointcut("execution(* com..*(..))")
//    @Pointcut("execution(* com.itheima.admin.controller..findAll())")

    @Pointcut("execution(* com.itheima.admin.controller.*.*(..))&&!execution(* com.itheima.admin.controller.AdminController.login(..)) &&!execution(* com.itheima.admin.controller.*.find*(..))")
    public void request(){}
    @Around("request()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //获取请求头
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        Enumeration<String> enumeration = request.getHeaderNames();
        StringBuffer headers = new StringBuffer();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headers.append(name + ":" + value).append(",");
        }
        log.info("headers:{}",headers);
        String pattern="token:([\\w\\.]*)";
        Pattern r = Pattern.compile(pattern);
        Matcher m=r.matcher(headers);
        String token=null;
        if (m.find()){
            token= m.group(1);
            log.info("找到了Token{}",m.group());
        }
        if (token==null||token.length()==0||token.equals("null")){
            log.info("回去了");
            return Result.error();
        }
//        log.info("token:{}",token);
        boolean verify = JWT.of(token).setKey("336699".getBytes()).verify();
        if (verify) {
            log.info("token正确，放行");
            Object proceed = pjp.proceed();
            return proceed;
        }
        return Result.error();
    }
}
